/*
 * Copyright (C), 2002-2017, 上海亦寻信息技术有限公司
 * FileName: ProjectPremisesIndustDataServiceImpl.java
 * Author:   linyao
 * Date:     2017-3-13 下午5:23:55
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.emm.yixun.website.service.estate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.common.enums.IndustMarkEnums;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.IndustDataVersion;
import com.emm.yixun.common.model.PmoSaleData;
import com.emm.yixun.common.model.ProjectBuilding;
import com.emm.yixun.common.model.ProjectPremises;
import com.emm.yixun.common.model.ProjectPremisesIndustData;
import com.emm.yixun.common.model.ProjectPremisesIndustDataVersion;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.dto.ProjectPremisesIndustDataDto;
import com.emm.yixun.common.model.dto.ProjectPremisesIndustDataVersionDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.ViewVersion;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.TargetTypeEnum;
import com.emm.yixun.common.model.enums.VersionEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.ListPage;
import com.emm.yixun.common.utils.MathUtil;
import com.emm.yixun.estate.service.ProjectBuildingServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesIndustDataServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesIndustDataVersionServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.website.common.utils.MathUtils;
import com.emm.yixun.website.vo.estate.IndustData;
import com.emm.yixun.website.vo.estate.PremisesIndustDatas;
/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 * 
 * @author linyao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class ProjectPremisesIndustDataServiceImpl implements ProjectPremisesIndustDataService {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private ProjectPremisesIndustDataServiceFacade projectPremisesIndustDataServiceFacade;
	
	@Autowired
	private ProjectPremisesIndustDataVersionServiceFacade projectPremisesIndustDataVersionServiceFacade;
	
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	
	
	@Autowired
	private ProjectPremisesServiceFacade projectPremisesServiceFacade;
	
	@Autowired
	private ProjectBuildingServiceFacade projectBuildingServiceFacade;
	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;
	

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.emm.yixun.website.service.estate.ProjectPremisesIndustDataService#save(com.emm.yixun.common.model.dto.
	 * ProjectPremisesIndustDataDto)
	 */
	@Override
	public void save(PremisesIndustDatas premisesIndustDatas, Long premisesId) throws Exception {
		List<IndustData> list = premisesIndustDatas.getData();
		ProjectPremisesIndustDataDto dataDto = new ProjectPremisesIndustDataDto();
		ListPage<IndustData> resultListPage = new ListPage<IndustData>();
		dataDto.setPremisesId(premisesId);
		Response<Boolean> response = projectPremisesIndustDataServiceFacade.destroy(dataDto);
		int rowColumn=21;
		List<ProjectPremisesIndustDataVersionDto> list1=new ArrayList<ProjectPremisesIndustDataVersionDto>();
		if (response.isSuccess()) {
			for (int j = 1; j <= list.size() / rowColumn; j++) {
				//获取第一行的值
				List<IndustData> result = resultListPage.page(j, rowColumn, list);
				//保存业态信息
				for (int i = 0; i <9;i++) {
					IndustData data = result.get(i);
					if (i == 0)
						dataDto.setIndustMark(StringUtils.isNotBlank(data.getValue()) ? data.getValue() : null);
					if (i == 1)
						dataDto.setSelfSustaiAcreag(StringUtils.isNotBlank(data.getValue()) ? new BigDecimal(data
								.getValue()) : null);
					if (i == 2)
						dataDto.setNumberOfBuildi(StringUtils.isNotBlank(data.getValue()) ? Integer.valueOf(data
								.getValue()) : null);
					if (i == 3)
						dataDto.setNumberLayers(StringUtils.isNotBlank(data.getValue()) ? Integer.valueOf(data
								.getValue()) : null);
					if (i == 4)
						dataDto.setTotalHouse(StringUtils.isNotBlank(data.getValue()) ? Integer.valueOf(data.getValue())
								: null);
					if (i == 5)
						dataDto.setSalableAcreag(StringUtils.isNotBlank(data.getValue()) ? new BigDecimal(data
								.getValue()) : null);
					if (i == 6)
						dataDto.setGroundSalesAcreag(StringUtils.isNotBlank(data.getValue()) ? new BigDecimal(data
								.getValue()) : null);
					if (i == 7)
						dataDto.setUndergSalesAcreag(StringUtils.isNotBlank(data.getValue()) ? new BigDecimal(data
								.getValue()) : null);	
					if (i == 8)
						dataDto.setTargetValue(StringUtils.isNotBlank(data.getValue()) ? new BigDecimal(data
								.getValue()) : null);
					
				}
				dataDto.setPremisesId(premisesId);

				Response<ProjectPremisesIndustDataDto> response1=projectPremisesIndustDataServiceFacade.save(dataDto);
				dataDto = new ProjectPremisesIndustDataDto();
				

				
				Date now=new Date();
				int index=8;
				for(int ii=1;ii<=6;ii++){
					index++;
					IndustData effectStartTime = result.get(index);
					index++;
					IndustData versionValue = result.get(index);
					if(StringUtils.isNotBlank(effectStartTime.getValue()) && StringUtils.isNotBlank(versionValue.getValue()) ){
						ProjectPremisesIndustDataVersionDto ppidv=new ProjectPremisesIndustDataVersionDto();
						ppidv.setIndustId(response1.getEntity().getId());
						ppidv.setPremisesId(premisesId);
						if(ii==1 || ii==7 || ii==13){
							ppidv.setVersionName("拓展版");
						}else if(ii==2 || ii==8 || ii==14){
							ppidv.setVersionName("启动会版");
						}else if(ii==3 || ii==9 || ii==15){
							ppidv.setVersionName("方案版");
						}else if(ii==4 || ii==10 || ii==16){
							ppidv.setVersionName("施工图版");
						}else if(ii==5 || ii==11 || ii==17){
							ppidv.setVersionName("结算版");
						}else if(ii==6 || ii==12 || ii==18){
							ppidv.setVersionName("经营计划版");
						}
						ppidv.setEffectStartTime(DateUtils.StringToDate(effectStartTime.getValue(), DateStyle.YYYY_MM_DD));
						ppidv.setVersionValue(new BigDecimal(versionValue.getValue()));
						ppidv.setTargetType("1");
						ppidv.setDelFlag("0");
						ppidv.setCreateTime(now);
						list1.add(ppidv);
					}
					
				}	
			}
			//保存目标销售均价
			//保存车位目标销售均价
			//保存目标货值
			if(null!=list1 && list1.size()>0){
				//批量删除
				ProjectPremisesIndustDataVersionDto deleteDto=new ProjectPremisesIndustDataVersionDto();
				deleteDto.setPremisesId(premisesId);
				projectPremisesIndustDataVersionServiceFacade.deleteByBatch(deleteDto);
				//批量保存
				projectPremisesIndustDataVersionServiceFacade.insertByBatch(list1);
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.website.service.estate.ProjectPremisesIndustDataService#findListByDto(com.emm.yixun.common.model
	 * .dto.ProjectPremisesIndustDataDto)
	 */
	@Override
	public List<ProjectPremisesIndustData> findListByDto(ProjectPremisesIndustDataDto dataDto) {
		ResponseList<ProjectPremisesIndustData> responseList = projectPremisesIndustDataServiceFacade
				.findByDto(dataDto);
		if (responseList.isSuccess()) {
			List<ProjectPremisesIndustData> list = responseList.getEntity();
			if(null != list){
				for(ProjectPremisesIndustData ppid : list){
					IndustDataVersion industDataVersion=queryIndustDataVersion(ppid.getId());
					ppid.setIndustDataVersion(industDataVersion);
				}
			}
			return list;
		} else {
			logger.error("查询失败");
		}
		return null;
	}
	
	private IndustDataVersion queryIndustDataVersion(Long industId){
		IndustDataVersion industDataVersion=new IndustDataVersion();
		ProjectPremisesIndustDataVersionDto industDataVersionDto=new ProjectPremisesIndustDataVersionDto();
		industDataVersionDto.setIndustId(industId);
		ResponseList<ProjectPremisesIndustDataVersion> responseList=projectPremisesIndustDataVersionServiceFacade.findByDto(industDataVersionDto);
		if(responseList.isSuccess() && null!=responseList.getEntity()){
			List<ProjectPremisesIndustDataVersion> industDataVersionList=responseList.getEntity();
			for(ProjectPremisesIndustDataVersion version : industDataVersionList){
				String targetType=version.getTargetType();
				String versionName=version.getVersionName();
				BigDecimal versionValue=version.getVersionValue();
				Date effectStartTime=version.getEffectStartTime();
				String  effectStartTimeStr="";
				if(null!=effectStartTime){
					effectStartTimeStr=DateUtils.DateToString(effectStartTime, DateStyle.YYYY_MM_DD);
				}
				//1.目标销售均价;2.车位目标销售均价;3.目标货值
				if(targetType.equals("1")){
					//目标销售均价-拓展版||启动会版||方案版||施工图版||结算版||经营计划版
					if(versionName.equals(TargetTypeEnum.VALUE_1.getNo())){
						industDataVersion.setValue1(effectStartTimeStr);
						industDataVersion.setValue2(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_2.getNo())){
						industDataVersion.setValue3(effectStartTimeStr);
						industDataVersion.setValue4(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_3.getNo())){
						industDataVersion.setValue5(effectStartTimeStr);
						industDataVersion.setValue6(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_4.getNo())){
						industDataVersion.setValue7(effectStartTimeStr);
						industDataVersion.setValue8(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_5.getNo())){
						industDataVersion.setValue9(effectStartTimeStr);
						industDataVersion.setValue10(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_6.getNo())){
						industDataVersion.setValue11(effectStartTimeStr);
						industDataVersion.setValue12(versionValue.toString());
					}
				}else if(targetType.equals("2")){
					//车位目标销售均价-拓展版||启动会版||方案版||施工图版||结算版||经营计划版
					if(versionName.equals(TargetTypeEnum.VALUE_1.getNo())){
						industDataVersion.setValue13(effectStartTimeStr);
						industDataVersion.setValue14(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_2.getNo())){
						industDataVersion.setValue15(effectStartTimeStr);
						industDataVersion.setValue16(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_3.getNo())){
						industDataVersion.setValue17(effectStartTimeStr);
						industDataVersion.setValue18(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_4.getNo())){
						industDataVersion.setValue19(effectStartTimeStr);
						industDataVersion.setValue20(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_5.getNo())){
						industDataVersion.setValue21(effectStartTimeStr);
						industDataVersion.setValue22(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_6.getNo())){
						industDataVersion.setValue23(effectStartTimeStr);
						industDataVersion.setValue24(versionValue.toString());
					}
				}else if(targetType.equals("3")){
					//目标货值-拓展版||启动会版||方案版||施工图版||结算版||经营计划版
					if(versionName.equals(TargetTypeEnum.VALUE_1.getNo())){
						industDataVersion.setValue25(effectStartTimeStr);
						industDataVersion.setValue26(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_2.getNo())){
						industDataVersion.setValue27(effectStartTimeStr);
						industDataVersion.setValue28(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_3.getNo())){
						industDataVersion.setValue29(effectStartTimeStr);
						industDataVersion.setValue30(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_4.getNo())){
						industDataVersion.setValue31(effectStartTimeStr);
						industDataVersion.setValue32(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_5.getNo())){
						industDataVersion.setValue33(effectStartTimeStr);
						industDataVersion.setValue34(versionValue.toString());
					}else if(versionName.equals(TargetTypeEnum.VALUE_6.getNo())){
						industDataVersion.setValue35(effectStartTimeStr);
						industDataVersion.setValue36(versionValue.toString());
					}
				}
			}
		}
		return industDataVersion;
	}

	@Override
	public List<ViewVersion> findViewVersion(ProjectPremisesIndustData data) {
		List<ViewVersion> array = new ArrayList<ViewVersion>();
		PmoSaleData response = projectServiceFacade.selPmoSaleData(null, data.getPremisesId(), IndustMarkEnums.getByName(data.getIndustMark()).getCode(), null);
		try {
			List<String> StringValue = new ArrayList<String>();
			ProjectPremisesIndustDataVersionDto ppidvd=new ProjectPremisesIndustDataVersionDto();
			ppidvd.setIndustId(data.getId());
			ppidvd.setTargetType("1");
			ppidvd.setOrders(" t.effect_start_time desc ");
			List<ProjectPremisesIndustDataVersion> ppidvdList=projectPremisesIndustDataVersionServiceFacade.findByDto(ppidvd).getEntity();
			if(null!=ppidvdList&&ppidvdList.size()>0){
				StringValue.add(ppidvdList.get(0).getVersionValue()+"");
			}
		
		
			/*StringValue.add(version.getValue2());
			StringValue.add(version.getValue4());
			StringValue.add(version.getValue6());
			StringValue.add(version.getValue8());
			StringValue.add(version.getValue10());
			StringValue.add(version.getValue12());*/
			for (int i = 0; i < StringValue.size(); i++) {
				if(response!=null){
					PmoSaleData saleData = response;
					array.addAll(getResult(StringValue.get(i), data.getSalableAcreag(), data.getTargetValue(), saleData.getTotalSignAmount(), saleData.getTotalCalculateArea(),data.getIndustMark(),data.getPremisesId()));
				}
			}
		} catch (Exception e) {
			logger.error("findViewVersion error: ", e);
		}
		return array;
	}
	/**
	* 方法描述 : 得到目标货值
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： ProjectPremisesIndustDataServiceImpl.java
	* 版本： v1.0
	* 创建时间： 2017年3月27日 下午7:46:38
	* @param value 目标均价
	* @param salableAcreag 可售面积
	* @param targetValue 自持货值
	* @return BigDecimal
	 */
	
	
	public List<ViewVersion> getResult(String value,BigDecimal salableAcreag,BigDecimal targetValue,BigDecimal totalSignAmount,BigDecimal totalCalculateArea,String IndustMark,Long premisesId){
		BigDecimal bigDecimal = new BigDecimal("0");
		String key = "-";
		List<ViewVersion> array = new ArrayList<ViewVersion>();
		array.add(new ViewVersion(key,StringUtils.isEmpty(value)==true?bigDecimal:new BigDecimal(value)));
		array.add(new ViewVersion("count",getTagValue(value, salableAcreag, targetValue,IndustMark,premisesId)));
		array.add(new ViewVersion(key, getDynamic(value, totalSignAmount, totalCalculateArea, salableAcreag,IndustMark, premisesId)));
		return array;
	}
	public BigDecimal getTagValue(String value,BigDecimal salableAcreag,BigDecimal targetValue,String IndustMark,Long premisesId){
		BigDecimal valueResult = new BigDecimal("0");
		BigDecimal zreo = new BigDecimal("0");
		BigDecimal val = new BigDecimal(StringUtils.isEmpty(value)==true?"0":value);
		salableAcreag=salableAcreag==null?zreo:salableAcreag;
		if(!IndustMark.equals(IndustMarkEnums.INDUSTMARKENUMS_UNDGERPARKINSPACE.getName())&&!IndustMark.equals(IndustMarkEnums.INDUSTMARKENUMS_GROUNDPARKINSPACE.getName())){
			salableAcreag=salableAcreag.multiply(new BigDecimal("10000"));
		}
		targetValue=targetValue==null?zreo:targetValue;
		valueResult=val.multiply(salableAcreag).add(targetValue);
		return valueResult;
	}
	/**
	* 方法描述 : 动态均价
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： ProjectPremisesIndustDataServiceImpl.java
	* 版本： v1.0
	* 创建时间： 2017年3月27日 下午8:16:04
	* @param value 目标均价
	* @param totalSignAmount 实际销售额
	* @param totalCalculateArea 已售面积
	* @param salableAcreag 可售面积
	* @return BigDecimal
	 */
	public BigDecimal getDynamic(String value,BigDecimal totalSignAmount,BigDecimal totalCalculateArea,BigDecimal salableAcreag,String IndustMark,Long premisesId){
		BigDecimal valueResult = new BigDecimal("0");
		BigDecimal zreo = new BigDecimal("0");
		BigDecimal val = new BigDecimal(StringUtils.isEmpty(value)==true?"0":value);
		totalSignAmount=totalSignAmount==null?zreo:totalSignAmount;
		totalSignAmount=totalSignAmount.divide(new BigDecimal("10000"));
		totalCalculateArea=totalCalculateArea==null?zreo:totalCalculateArea;
		salableAcreag=salableAcreag==null?zreo:salableAcreag;
		if(!IndustMark.equals(IndustMarkEnums.INDUSTMARKENUMS_UNDGERPARKINSPACE.getName())&&!IndustMark.equals(IndustMarkEnums.INDUSTMARKENUMS_GROUNDPARKINSPACE.getName())){
			salableAcreag=salableAcreag.multiply(new BigDecimal("10000"));
			
		}else{
			PmoSaleData response = projectServiceFacade.selPmoSaleData(null, premisesId, IndustMarkEnums.getByName(IndustMark).getCode(), "2");
			totalCalculateArea=new BigDecimal(response.getTotalRowCount());
		}
		//实际销售额 
		//未售面积=可售面积-已售面积
		//动态货值=实际销售额+目标销售均价（分期）*未售面积（目标均价到分期）
		//动态均价=动态货值/可售面积
		BigDecimal signAmount  =val.multiply(salableAcreag.subtract(totalCalculateArea)).add(totalSignAmount);
		valueResult=new BigDecimal(MathUtils.divide(signAmount, salableAcreag, 4));
		return valueResult;
	}

	@Override
	public List<ProjectPremisesIndustData> findProjectPremisesIndustData(ProjectPremises premises) {
		List<ProjectPremisesIndustData> industData = new ArrayList<ProjectPremisesIndustData>();
		try {
			ProjectPremisesIndustDataDto dataDto = new ProjectPremisesIndustDataDto();
			dataDto.setPremisesId(premises.getId());
			
			List<ProjectPremisesIndustData> datas = findListByDto(dataDto);
			if (datas != null && datas.size() > 0) {
				BigDecimal zreo = new BigDecimal("0");
				for (ProjectPremisesIndustData projectPremisesIndustData : datas) {
					if(projectPremisesIndustData.getSelfSustaiAcreag()==null)
						projectPremisesIndustData.setSelfSustaiAcreag(zreo);
					if(projectPremisesIndustData.getSalableAcreag()==null)
						projectPremisesIndustData.setSalableAcreag(zreo);
					if(projectPremisesIndustData.getTargetAveragPrice()==null)
						projectPremisesIndustData.setTargetAveragPrice(zreo);
					if(projectPremisesIndustData.getTargetValue()==null)
						projectPremisesIndustData.setTarget(zreo);
					String industMarks = projectPremisesIndustData.getIndustMark();
					if(null!=projectPremisesIndustData.getIndustMark()){
						projectPremisesIndustData.setIndustMark(IndustMarkEnums.getByCode(projectPremisesIndustData.getIndustMark()).getName());
					}
					PmoSaleData entitySale=projectServiceFacade.queryPmoArae(projectPremisesIndustData.getPremisesId(), industMarks);
					//组团ID,业态  得到已售面积
					List<ViewVersion> array = findViewVersion(projectPremisesIndustData);
					projectPremisesIndustData.setArray(array);
					BigDecimal totalSignAmount = new BigDecimal("0");
					BigDecimal totalCalculateArea =new BigDecimal("0");
					/*BigDecimal v10 = new BigDecimal("0");*/
					BigDecimal v8 = new BigDecimal("0");
					ProjectPremisesIndustDataVersionDto ppidvd=new ProjectPremisesIndustDataVersionDto();
					ppidvd.setIndustId(projectPremisesIndustData.getId());
					ppidvd.setTargetType("1");
					ppidvd.setOrders(" t.effect_start_time desc ");
					Response<ProjectPremises> premisesRes = projectPremisesServiceFacade.findById(projectPremisesIndustData.getPremisesId());
					if(premisesRes.isSuccess()&&premisesRes.getEntity()!=null){
						projectPremisesIndustData.setpName(premisesRes.getEntity().getGroupName());
					}
					List<ProjectPremisesIndustDataVersion> ppidvdList=projectPremisesIndustDataVersionServiceFacade.findByDto(ppidvd).getEntity();
					if(null==ppidvdList || ppidvdList.size()<=0)continue;
					ProjectPremisesIndustDataVersion ppidv=ppidvdList.get(0);
					
					BigDecimal number = new BigDecimal("10000");
					BigDecimal v1=ppidv.getVersionValue()==null?zreo:ppidv.getVersionValue(); //最新版本的目标均价
					if(industMarks.equals(IndustMarkEnums.INDUSTMARKENUMS_GROUNDPARKINSPACE.getCode())||industMarks.equals(IndustMarkEnums.INDUSTMARKENUMS_UNDGERPARKINSPACE.getCode())){
						PmoSaleData pmo = projectServiceFacade.selPmoSaleData(null, projectPremisesIndustData.getPremisesId(), industMarks, "2");
						if(pmo!=null){
							totalSignAmount = pmo.getTotalSignAmount(); 
							projectPremisesIndustData.setTotalCalculateArea(new BigDecimal(pmo.getTotalRowCount())); //是车位  /个数
							totalCalculateArea=new BigDecimal(pmo.getTotalRowCount());
							/*v10=v10.add(new BigDecimal(pmo.getTotalRowCount()));*/
							projectPremisesIndustData.setDynamicValue(totalSignAmount.divide(new BigDecimal("10000")).add(v1.multiply(projectPremisesIndustData.getSalableAcreag().subtract(new BigDecimal(pmo.getTotalRowCount())))));
						}
					}else{
						PmoSaleData responseSalaData = projectServiceFacade.selPmoSaleData(null, projectPremisesIndustData.getPremisesId(), industMarks, null);
						if(responseSalaData!=null){
							totalSignAmount = responseSalaData.getTotalSignAmount()==null?zreo:responseSalaData.getTotalSignAmount(); 
							totalCalculateArea = entitySale.getTotalCalculateArea();
							projectPremisesIndustData.setTotalCalculateArea(entitySale.getTotalCalculateArea().divide(new BigDecimal("10000")));
							/*v10=entitySale.getTotalCalculateArea().multiply(new BigDecimal("10000"));*/
							BigDecimal v12 = projectPremisesIndustData.getSalableAcreag().multiply(new BigDecimal("10000")); //可售面积
							BigDecimal v13 = v12.subtract(entitySale.getTotalCalculateArea());
							BigDecimal v11 = totalSignAmount.divide(new BigDecimal("10000")).add(v1.multiply(v13));
							projectPremisesIndustData.setDynamicValue(v11);
							projectPremisesIndustData.setSaleValue(responseSalaData.getTotalSignAmount().divide(new BigDecimal("10000")));
						}
						
					}
				
					
					
					//获取生效日期最新的值
					
					BigDecimal v2 = projectPremisesIndustData.getSalableAcreag()==null?zreo:projectPremisesIndustData.getSalableAcreag();//业态的可售面积
					BigDecimal v3 = projectPremisesIndustData.getTargetValue()==null?zreo:projectPremisesIndustData.getTargetValue();//自持货值
					BigDecimal v4 = new BigDecimal("0");
					
					//最新版本的目标均价*业态的可售面积*10000+自持货值
					if(industMarks.equals(IndustMarkEnums.INDUSTMARKENUMS_GROUNDPARKINSPACE.getCode())||industMarks.equals(IndustMarkEnums.INDUSTMARKENUMS_UNDGERPARKINSPACE.getCode())){
						v8=projectPremisesIndustData.getSalableAcreag();
						v4 = v1.multiply(v2).add(v3);
						
					}else{
						v8=projectPremisesIndustData.getSalableAcreag().multiply(number);
						 v4 = v1.multiply(v2).multiply(number).add(v3);
					}
					
					//目标货值-实际销售
					BigDecimal results =v4.subtract(totalSignAmount.divide(number));
					BigDecimal bg = v8.subtract(totalCalculateArea);
					double v5 = MathUtil.divide(results, new BigDecimal("1"), 4);
					double v6 = MathUtils.divide(new BigDecimal(v5), bg,4);
					BigDecimal v7 =new BigDecimal(v6);
					projectPremisesIndustData.setLastPrice(v7);
					projectPremisesIndustData.setTargetSaleValue(v1.multiply(projectPremisesIndustData.getSalableAcreag()).multiply(new BigDecimal("10000")));
					//未收面积= 可售- 已收
					//动态货值 = 实际销售额+（目标销售均价*未售面积）
					
					
					
				}
				industData.addAll(datas);
			}
		} catch (Exception e) {
			logger.error("findProjectPremisesIndustData error: ", e);
		}
		return industData;
	
	}

	@Override
	public HashMap<String, BigDecimal> getTargetValue(Long preId) {
		HashMap<String, BigDecimal> map = new HashMap<String, BigDecimal>();
		//查询组团对应的业态
		ProjectPremisesIndustDataDto dataDto = new ProjectPremisesIndustDataDto();
		dataDto.setPremisesId(preId);
		List<ProjectPremisesIndustData> datas = findListByDto(dataDto);
		if (datas != null && datas.size() > 0) {
			//目标货值 车位
			BigDecimal zero = new BigDecimal("0");
			BigDecimal bdm = zero;
			BigDecimal totalCount = zero;
			BigDecimal industCarResult = zero;
			//已售面积
			BigDecimal totalCalculateArea=zero;
			//房间实际销售金额
			BigDecimal totalSignAmount = zero;
			//房间最新目标销售均价累计
			BigDecimal roomVersionValue = zero;
			//车位最新目标销售均价累计
			BigDecimal carVersionValue = zero;
			// 车位已收之和
			BigDecimal carTotalCount = zero;
			//车位实际销售额之和
			BigDecimal carSaleCount = zero;
			//房子
			BigDecimal bdm_f = zero;
			BigDecimal totalCount_f= zero;
			//可售面积不计算车位
			BigDecimal salableAcreag_nc = zero;
			//自持面积不计算车位
			BigDecimal selfSustaiAcreag = zero;
			//栋数
			BigDecimal numberOfBuildi = zero;
			//总户数
			BigDecimal totalHouse = zero;
			//地下停车场面积
			BigDecimal groundSalesAcreag = zero; //地上
			BigDecimal undergSalesAcreag = zero; //地下
			//目标销售收入
			BigDecimal targetSaleMoney = zero;
			//车位目标销售收入
			BigDecimal carTargetValue = zero;
			BigDecimal r1 = zero; //房间累计
			BigDecimal r2 = zero;// 车位累计
			for (ProjectPremisesIndustData projectPremisesIndustData : datas) {
				if(projectPremisesIndustData.getSelfSustaiAcreag()==null)
					projectPremisesIndustData.setSelfSustaiAcreag(zero);
				if(projectPremisesIndustData.getSalableAcreag()==null)
					projectPremisesIndustData.setSalableAcreag(zero);
				if(projectPremisesIndustData.getTargetAveragPrice()==null)
					projectPremisesIndustData.setTargetAveragPrice(zero);
				if(projectPremisesIndustData.getTargetValue()==null)
					projectPremisesIndustData.setTarget(zero);
				ProjectPremisesIndustDataVersionDto ppidvd=new ProjectPremisesIndustDataVersionDto();
				ppidvd.setIndustId(projectPremisesIndustData.getId());
				ppidvd.setTargetType("1");
				ppidvd.setOrders(" t.effect_start_time desc ");
				List<ProjectPremisesIndustDataVersion> ppidvdList=projectPremisesIndustDataVersionServiceFacade.findByDto(ppidvd).getEntity();
				if(null==ppidvdList || ppidvdList.size()<=0)continue;
				//获取生效日期最新的值
				ProjectPremisesIndustDataVersion ppidv=ppidvdList.get(0);
				//最新目标销售均价* 可售车位 + 自持货值 = 目标货值
				BigDecimal v1=ppidv.getVersionValue()==null?new BigDecimal("0"):ppidv.getVersionValue();
				if(projectPremisesIndustData.getIndustMark().equals(IndustMarkEnums.INDUSTMARKENUMS_GROUNDPARKINSPACE.getCode())||projectPremisesIndustData.getIndustMark().equals(IndustMarkEnums.INDUSTMARKENUMS_UNDGERPARKINSPACE.getCode())){
						BigDecimal row = projectPremisesIndustData.getSalableAcreag();
						totalCount=totalCount.add(row);
						bdm=bdm.add(v1.multiply(row));
						if(null!=projectPremisesIndustData.getTargetValue()){
							bdm=bdm.add(projectPremisesIndustData.getTargetValue());
						}
						carVersionValue = carVersionValue.add(v1);
						PmoSaleData pmo = projectServiceFacade.selPmoSaleData(null, projectPremisesIndustData.getPremisesId(), projectPremisesIndustData.getIndustMark(), "2");
						if(pmo!=null){
							Long rowCount = pmo.getTotalRowCount()==null?0L:pmo.getTotalRowCount();
							BigDecimal saleCount = pmo.getTotalSignAmount()==null?zero:pmo.getTotalSignAmount();
							carTotalCount=carTotalCount.add(new BigDecimal(rowCount));
							carSaleCount=carSaleCount.add(saleCount);
							
						}
						r2=r2.add(v1.multiply(row.subtract(pmo.getTotalRowCount()==null?zero:new BigDecimal(pmo.getTotalRowCount()))));
						carTargetValue = carTargetValue.add(projectPremisesIndustData.getSalableAcreag().multiply(v1));
				}else{
					//房间实际销售金额
					PmoSaleData responseSalaData = projectServiceFacade.selPmoSaleData(null, projectPremisesIndustData.getPremisesId(),projectPremisesIndustData.getIndustMark(),null);
					if(responseSalaData!=null){
						PmoSaleData sale = responseSalaData;
						totalCalculateArea=totalCalculateArea.add(sale.getTotalCalculateArea()==null?zero:sale.getTotalCalculateArea());
						totalSignAmount = totalSignAmount.add(sale.getTotalSignAmount()==null?zero:sale.getTotalSignAmount());
					}
					
					//可售面积
					BigDecimal row = projectPremisesIndustData.getSalableAcreag();
					totalCount_f=totalCount_f.add(row);
					row=row.multiply(new BigDecimal("10000"));
					BigDecimal temp=v1.multiply(row);
                    if(null!=projectPremisesIndustData.getTargetValue()){
                    	  temp=temp.add(projectPremisesIndustData.getTargetValue());
					}
					bdm_f=bdm_f.add(temp);
					
					roomVersionValue=roomVersionValue.add(v1);
					salableAcreag_nc = salableAcreag_nc .add(projectPremisesIndustData.getSalableAcreag());	
					selfSustaiAcreag = selfSustaiAcreag.add(projectPremisesIndustData.getSelfSustaiAcreag());
					numberOfBuildi = numberOfBuildi.add(projectPremisesIndustData.getNumberOfBuildi()==null?zero:new BigDecimal(projectPremisesIndustData.getNumberOfBuildi()));
					totalHouse=totalHouse.add(projectPremisesIndustData.getTotalHouse()==null?zero:new BigDecimal(projectPremisesIndustData.getTotalHouse()));
					groundSalesAcreag = groundSalesAcreag.add(projectPremisesIndustData.getGroundSalesAcreag());
					undergSalesAcreag = undergSalesAcreag.add(projectPremisesIndustData.getUndergSalesAcreag());
					targetSaleMoney = targetSaleMoney.add(projectPremisesIndustData.getSalableAcreag().multiply(new BigDecimal("10000").multiply(v1)));
					//——————————————————————
					//目标销售均价*未售面积
					
					r1=r1.add(v1.multiply(row.subtract(responseSalaData.getTotalCalculateArea()==null?zero:responseSalaData.getTotalCalculateArea())));
					
				}
			
			}
			//目标货值 / 可售之和 = 组团级别车位销售均价
			if(totalCount.compareTo(zero)!=0){
				bdm = new BigDecimal(MathUtils.divide(bdm,totalCount,4));
				if(bdm.compareTo(zero)==0){
					industCarResult=industCarResult.add(zero);
				}else{
					industCarResult=bdm;
					
				}
				map.put("carSaleReturn", MathUtils.divide(carSaleCount.divide(new BigDecimal("10000")).add(r2), totalCount));
			}else{
				map.put("carSaleReturn",zero);
			}
			
			map.put("industCar",industCarResult);
			BigDecimal bdm_fs = new BigDecimal(MathUtils.divide(bdm_f, totalCount_f.multiply(new BigDecimal("10000")),4));
			map.put("industRoom", bdm_fs);
			BigDecimal v1 = totalCount_f.multiply(new BigDecimal("10000")).subtract(totalCalculateArea);
			double v2 = new Double(bdm_f.toString()); //目标货值
			double v3 = new Double(totalSignAmount.toString())/10000;
			double result = (v2-v3)/new Double(v1.toString());
			map.put("industSigned", new BigDecimal(result));
			//未来销售最低均价 = （房间目标货值-房间实际销售金额）/ 可售面积只和-房间已售只和
			
			//动态均价= （实际销售额只和+(目标销售均价之和*（可售之和—已售只和）)）/可售只和
			// v3 = 实际销售之和
			//roomVersionValue = 目标销售均价之和
			//动态货值 = 实际销售额+（目标销售均价*未售面积） (面积)
			
			/*BigDecimal v7 = new BigDecimal(v3).add(roomVersionValue.multiply(v1));*/
			
			map.put("indusRoomVer", MathUtils.divide(totalSignAmount.divide(new BigDecimal("10000")).add(r1), totalCount_f.multiply(new BigDecimal("10000"))));
		
			
			//动态货值 = 实际销售额+（目标销售均价*未售面积） (车位)
			
			
			map.put("totalCalculateArea", totalCalculateArea.divide(new BigDecimal("10000")));
			
			
			
			
			//车位动态均价=carVersionValue    可售只和 = totalCount  //车位已售只和 carTotalCount   //实际销售额= carSaleCount
		/*	BigDecimal v9 = carVersionValue.multiply(totalCount.subtract(carTotalCount));
			
			double v18 = MathUtils.divide(carSaleCount, new BigDecimal("10000"), 4);
			if(totalCount.compareTo(zero)==0){
				map.put("carSaleReturn", zero);
			}else{
				double v19 = MathUtils.divide(new BigDecimal(MathUtils.add(v18, new Double(v9.toString()))), totalCount, 4);
				map.put("carSaleReturn", new BigDecimal(v19));
			}*/
		
			map.put("salableAcreag_nc", salableAcreag_nc);
			//动态货值（含车位的动态货值） 房间的实际销售额
			// 房间的动态货值 ：v7;  车位动态货值 v18 + v9
			map.put("dynamicValue", zero);
			map.put("selfSustaiAcreag", selfSustaiAcreag);
			map.put("numberOfBuildi", numberOfBuildi);
			map.put("totalHouse", totalHouse);
			map.put("groundSalesAcreag", groundSalesAcreag);
			map.put("undergSalesAcreag", undergSalesAcreag);
			map.put("targetSaleMoney", targetSaleMoney);
			map.put("carTargetValue", carTargetValue);
		}
		return map;
	}

	@Override
	public void industDataSave(ProjectPremisesIndustDataDto premisesIndustDataDto, Long budingId) {
	    	premisesIndustDataDto.setIndustType("2");
		Response<ProjectBuilding> responseBuilding = projectBuildingServiceFacade.findById(budingId);
		ProjectBuilding projectBuilding = responseBuilding.getEntity();
		Long industId = null;
		ProjectPremisesIndustDataDto query = new ProjectPremisesIndustDataDto();
		query.setBuildingId(budingId);
		ResponseList<ProjectPremisesIndustData> responseList = projectPremisesIndustDataServiceFacade.findByDto(query);
		if(responseList.isSuccess()&&responseList.getEntity()!=null&&responseList.getEntity().size()>0){
			industId = responseList.getEntity().get(0).getId();
		}
		ProjectPremisesIndustDataDto destroyDto = new ProjectPremisesIndustDataDto();
		destroyDto.setBuildingId(budingId);
		projectPremisesIndustDataServiceFacade.destroy(destroyDto);
		
		//获得最新版本的
		//最新的生效时间
		if(premisesIndustDataDto.getVersionDate()!=null&&premisesIndustDataDto.getVersionDate().size()>0){
			String maxValue = Collections.max(premisesIndustDataDto.getVersionDate());
			if(maxValue!=null&&maxValue!=""){
				int maxIndex = premisesIndustDataDto.getVersionDate().indexOf(maxValue);
				premisesIndustDataDto.setTargetAveragPrice(new BigDecimal(premisesIndustDataDto.getVersionValue().get(maxIndex)));
			}
		}
		premisesIndustDataDto.setProjectId(projectBuilding.getProjectId());
		premisesIndustDataDto.setPremisesId(projectBuilding.getPremisesId());
		premisesIndustDataDto.setBuildingId(projectBuilding.getId());
		Response<ProjectPremisesIndustDataDto> response = projectPremisesIndustDataServiceFacade.save(premisesIndustDataDto);
		
		//保存版本信息  -  先删除
		if(industId!=null){
			ProjectPremisesIndustDataVersionDto versionDto = new ProjectPremisesIndustDataVersionDto();
			versionDto.setIndustId(industId);
			projectPremisesIndustDataVersionServiceFacade.deleteByBatch(versionDto);
		}
		
		//保存版本信息
	
			for (int i = 0; i < premisesIndustDataDto.getVersionValue().size(); i++) {
				
				ProjectPremisesIndustDataVersionDto entity = new ProjectPremisesIndustDataVersionDto();
				entity.setIndustId(response.getEntity().getId());
				entity.setVersionName(VersionEnum.getByNo(i).getValue());
				//生效时间
				String effectTime = premisesIndustDataDto.getVersionDate().get(i);
				if(effectTime==null||effectTime==""){
					continue;
				}
				entity.setEffectStartTime(DateUtils.StringToDate(effectTime, DateStyle.YYYY_MM_DD.getValue()));
				String versionValue = premisesIndustDataDto.getVersionValue().get(i);
				if(versionValue==null||versionValue==""){
					continue;
				}
				entity.setVersionValue(new BigDecimal(versionValue));
				entity.setTargetType("1");
				entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				entity.setPremisesId(responseBuilding.getEntity().getPremisesId());
				projectPremisesIndustDataVersionServiceFacade.save(entity);
			}
			ProjectRoomDto roomQuery = new ProjectRoomDto();
			roomQuery.setBuildingId(budingId);
			ResponseList<ProjectRoom> responseListRoomList = projectRoomServiceFacade.findByDto(roomQuery);
			if(responseListRoomList.isSuccess()&&responseListRoomList.getEntity()!=null&&responseListRoomList.getEntity().size()>0){
				for (ProjectRoom room:responseListRoomList.getEntity()) {
					ProjectRoomDto updateRoom = new ProjectRoomDto();
					updateRoom.setId(room.getId());
					updateRoom.setIndustMark(premisesIndustDataDto.getIndustMark());
					projectRoomServiceFacade.updateByPrimaryKey(updateRoom, true);
				}
			}
	}

	@Override
	public HashMap<String, String> createProjectIndustData(ProjectPremisesIndustDataDto premisesIndustDataDto,Long projectId) {
	    	HashMap<String, String> map = new HashMap<String, String>();
        	if(premisesIndustDataDto.getVersionDate()!=null&&premisesIndustDataDto.getVersionDate().size()>0){
        		String maxValue = Collections.max(premisesIndustDataDto.getVersionDate());
        		if(maxValue!=null&&maxValue!=""){
        			int maxIndex = premisesIndustDataDto.getVersionDate().indexOf(maxValue);
        			if(StringUtils.isEmpty(premisesIndustDataDto.getVersionValue().get(maxIndex))){
        			    map.put("error", "请输入对应的版本值!");
        			    return map;
        			}
        			premisesIndustDataDto.setTargetAveragPrice(new BigDecimal(premisesIndustDataDto.getVersionValue().get(maxIndex)));
        		}
        	}
        	premisesIndustDataDto.setProjectId(projectId);
        	Long industId = null;
        	ProjectPremisesIndustDataDto queryProjectIndust = new ProjectPremisesIndustDataDto();
         	queryProjectIndust.setProjectId(projectId);
         	queryProjectIndust.setPremisesId(premisesIndustDataDto.getPremisesId());
         	queryProjectIndust.setBuildingId(premisesIndustDataDto.getBuildingId());
         	queryProjectIndust.setIndustMark(premisesIndustDataDto.getIndustMark());
         	queryProjectIndust.setIndustType(premisesIndustDataDto.getIndustType());
         	queryProjectIndust.setDelFlag(DelFlagEnum.UNDEL.getNo());
         	ResponseList<ProjectPremisesIndustData> queryList =  projectPremisesIndustDataServiceFacade.findByDto(queryProjectIndust);
         	BaseCodeValue baseCodeValue = baseCodeValueServiceFacade.findById(new Long(premisesIndustDataDto.getIndustMark())).getEntity();
         	if(baseCodeValue.getCodeValue().equals(IndustMarkEnums.INDUSTMARKENUMS_PARKINSPACE.getCode())){
         	    if(premisesIndustDataDto.getSalableAcreag()!=null){
         		if(!isInteger(premisesIndustDataDto.getSalableAcreag().toString())){
         		    map.put("error", "车位个数请输入正整数");
         		    return map;
         		}
         	    }
         	}
        	if(premisesIndustDataDto.getId()==null){
        	    if(queryList.isSuccess()&&queryList.getEntity()!=null&&queryList.getEntity().size()>0){
        		map.put("error", "不能重复新增相同的业态");
			return map;
        	    }
        	    Response<ProjectPremisesIndustDataDto> response = projectPremisesIndustDataServiceFacade.save(premisesIndustDataDto);
        	    industId = response.getEntity().getId();
        	}else{
        	    if(queryList.isSuccess()&&queryList.getEntity()!=null&&queryList.getEntity().size()>0){
        		if(premisesIndustDataDto.getId().compareTo(queryList.getEntity().get(0).getId())!=0){
        		    map.put("error", "业态已存在,请修改!");
        		    return map;
        		}
        	    }
        	    projectPremisesIndustDataServiceFacade.updateByPrimaryKey(premisesIndustDataDto, true);
        	    industId = premisesIndustDataDto.getId();
        	    //删除已经存在的版本信息
        	    ProjectPremisesIndustDataVersionDto versionDto = new ProjectPremisesIndustDataVersionDto();
        	    versionDto.setIndustId(industId);
        	    projectPremisesIndustDataVersionServiceFacade.deleteByBatch(versionDto);
        	}
        	
        	//保存版本信息
        	if(premisesIndustDataDto.getVersionValue()!=null){
        	    for (int i = 0; i < premisesIndustDataDto.getVersionValue().size(); i++) {
        		ProjectPremisesIndustDataVersionDto entity = new ProjectPremisesIndustDataVersionDto();
        		entity.setIndustId(industId);
        		entity.setVersionName(VersionEnum.getByNo(i).getValue());
        		//生效时间
        		String effectTime = premisesIndustDataDto.getVersionDate().get(i);
        		if(effectTime==null||effectTime==""){
        			continue;
        		}
        		entity.setEffectStartTime(DateUtils.StringToDate(effectTime, DateStyle.YYYY_MM_DD.getValue()));
        		String versionValue = premisesIndustDataDto.getVersionValue().get(i);
        		if(versionValue==null||versionValue==""){
        			continue;
        		}
        		entity.setVersionValue(new BigDecimal(versionValue));
        		entity.setTargetType("1");
        		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
        		projectPremisesIndustDataVersionServiceFacade.save(entity);
        		}
        	}
        	return map;
	}
	
	public static boolean isInteger(String str) {    
	    Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");    
	    return pattern.matcher(str).matches();    
	 }
}
